//
//  LoginViewController.m
//  Student
//
//  Created by 李飞 on 15/9/8.
//  Copyright (c) 2015年 XueYinYue. All rights reserved.
//

#import "LoginViewController.h"
#import "NSString+WPAttributedMarkup.h"
#import <CoreText/CoreText.h>
#import <SMS_SDK/SMS_SDK.h>
#import "RDVTabBarController.h"

#import "SetPasswordViewController.h"
#import "RegisterViewController.h"
#import "ForgetPasswordViewController.h"

@interface LoginViewController ()
{
    int _timeout;
    dispatch_source_t _timer;
    bool isPasswordLogin;
}

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.rdv_tabBarController.tabBarHidden = YES;
    self.title = @"用户短信验证登录";isPasswordLogin = NO;
    //隐藏错误提示信息
    _showPasswordBtn.hidden = YES;
    _errorSMGLab.hidden = YES;
    _loginBtn.enabled = NO;
    _forgetPasswordBtn.enabled = NO;
    
//    //调整textfield的输入框内输入文字距离
//    UIView* userPaddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 70, _userNameTF.frame.size.height)];
//    _userNameTF.leftView = userPaddingView;
//    _userNameTF.leftViewMode = UITextFieldViewModeAlways;
//
//    UIView* passPaddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 70, _identifyCodeTF.frame.size.height)];
//    _identifyCodeTF.leftView = passPaddingView;
//    _identifyCodeTF.leftViewMode = UITextFieldViewModeAlways;

   [self initNavegationBar];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 *  创建改变获取验证码按钮状态的定时器
 */
- (void)createTimer
{
    _timeout = 60;
    dispatch_queue_t queue = dispatch_queue_create("timer queue", 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        if (_timeout > 0)
        {
            _timeout -= 1;
            dispatch_async(dispatch_get_main_queue(), ^{
                [_getVerificationCodeButton setTitle:[NSString stringWithFormat:@"获取验证码(%ds)",_timeout] forState:UIControlStateDisabled];
                [_getVerificationCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                _getVerificationCodeButton.enabled = YES;
                [_getVerificationCodeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [_getVerificationCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            });
            dispatch_source_cancel(_timer);
        }
    });
    dispatch_source_set_cancel_handler(_timer, ^{
        //        NSLog(@"timer cancle");
        _timer = nil;
    });
    dispatch_resume(_timer);
}
#pragma mark -  错误提示
/**
 *  显示错误提示
*/
- (void)showErrorMessageTipsWithMessage:(NSString *)message
{
//    [UIView transitionWithView:_errorSMGLab duration:0.3 options:(UIViewAnimationOptionTransitionFlipFromTop | UIViewAnimationOptionCurveEaseOut) animations:^{
//        _errorSMGLab.hidden = NO;
 //       _errorSMGLab.text =message;
//    } completion:nil];
    
}
/**
 *  显示错误提示
 */
- (void)hiddenErrorMessageTips
{
//    [UIView transitionWithView:_errorSMGLab duration:0.3 options:(UIViewAnimationOptionTransitionFlipFromBottom | UIViewAnimationOptionCurveEaseOut) animations:^{
//
//        _errorSMGLab.hidden = YES;
//    } completion:nil];
    
}
/**
 *  输入号码检查
 */
- (BOOL)checkPhoneNum
{
    if (_userNameTF.text.length == 0)
    {
        _forgetPasswordBtn.enabled = NO;
    }
    if (_userNameTF.text.length == 11 &&  _userNameTF.text.length != 0) {
        _forgetPasswordBtn.enabled = YES;
         return YES;
    }
    else{
        [_userNameTF resignFirstResponder];        
        SHOW_ALERTVIEW(@"请正确输入手机号码", nil, 1, self);
        //[self showErrorMessageTipsWithMessage:@"请正确输入手机号码"];
        return NO;
    }
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (_userNameTF.text.length == 0 || _identifyCodeTF.text.length == 0 ) {
        _loginBtn.enabled = NO;
    }
    else
    {
        _loginBtn.enabled = YES;
    }

    if (textField == _userNameTF)
    {
        //获取用户信息并判断
        if (![self checkPhoneNum])
        {
            [_userNameTF becomeFirstResponder];
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -  事件响应

- (IBAction)onReceiveIdentifyingCodeButtonClick:(id)sender {
    //手机号码输入检测
    if ([self checkPhoneNum])
    {
        [self hiddenErrorMessageTips];
        
        _getVerificationCodeButton.enabled = NO;
        if (!_timer)
        {
            [self createTimer];
        }
        [SMS_SDK getVerificationCodeBySMSWithPhone:_userNameTF.text
                                              zone:@"86"
                                            result:^(SMS_SDKError *error) {
                                                NSLog(@"获取验证Error:%@",error);
                                            }];
    }
}

- (IBAction)onLoginbuttonClick:(id)sender {

    if ([self checkPhoneNum])
    {
        //验证码核对
        [SMS_SDK commitVerifyCode:_identifyCodeTF.text result:^(enum SMS_ResponseState state) {
            if (state == 0)
            {
                 SHOW_ALERTVIEW(@"验证码错误", nil, 0, self);
                
               // [self showErrorMessageTipsWithMessage:@"验证码错误"];
            }
            else
            {
                [self hiddenErrorMessageTips];
    NSLog(@"登录成功！");
            }
        }];
    }
    
}

- (IBAction)onForgetPasswordClick:(id)sender {
    
    ForgetPasswordViewController *forgetPasswordViewController = [[ForgetPasswordViewController alloc] initWithNibName:@"ForgetPasswordViewController" bundle:nil];
    [self.navigationController pushViewController:forgetPasswordViewController animated:YES];
    NSLog(@"执行完了");
}

- (IBAction)onChangeLoginStyeClick:(id)sender {
    isPasswordLogin = !isPasswordLogin;
    if (isPasswordLogin) {
        [_changeLoginStyleBtn setTitle: @"手机短信验证登录" forState:UIControlStateNormal];
        _getVerificationCodeButton.hidden = YES;
        _identifyCodeTF.placeholder = @"请输入登录密码";
        _identifyCodeTF.secureTextEntry = YES;
        _showPasswordBtn.hidden = NO;
    }
    else{
        [_changeLoginStyleBtn setTitle:@"账号密码登录" forState:UIControlStateNormal];
        
        _getVerificationCodeButton.hidden = NO;
        _identifyCodeTF.placeholder = @"请输入验证码";
        _showPasswordBtn.hidden = YES;
    }
}

- (IBAction)onShowPasswordClick:(id)sender {
    UIImage *image;
    _identifyCodeTF.secureTextEntry = !_identifyCodeTF.isSecureTextEntry;
    if (_identifyCodeTF.secureTextEntry)
    {
        image = [UIImage imageNamed:@"icon_eye_gray.png"];
    }
    else
    {
        image = [UIImage imageNamed:@"icon_eye_green.png"];
    }
    [_showPasswordBtn setImage:image forState:UIControlStateNormal];
}
#pragma mark -  NavegationBar

- (void)initNavegationBar
{
    
    //    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    //    backBtn.bounds = CGRectMake(0, 0, 15, 20);
    //    [backBtn addTarget:self action:@selector(onBackButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    //    [backBtn setBackgroundImage:[UIImage imageNamed:NAVIGATION_BACKARROW_IMAGE] forState:UIControlStateNormal];
    
    UIBarButtonItem *backBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(onBackButtonClick:)];
    UIBarButtonItem *registerBarBtn = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(onRegisterButtonClick:)];
    self.navigationItem.leftBarButtonItem = backBarBtn;
    self.navigationItem.rightBarButtonItem = registerBarBtn;
}

- (void)onRegisterButtonClick:(id)sender
{
    RegisterViewController *registerViewController = [[RegisterViewController alloc] initWithNibName:@"RegisterViewController" bundle:nil];
    [self.navigationController pushViewController:registerViewController animated:YES];
}

- (void)onBackButtonClick:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
